package com.mokylin.dbschema.util;

import com.mokylin.dbschema.config.ConfigInfo;
import com.mokylin.dbschema.config.ConfigKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author 李朝(Li.Zhao)
 * @since 2015/8/31.
 */

public class DBUtils {

    private static final Logger LOG = LoggerFactory.getLogger(DBUtils.class);

    private static  Connection connection;

    private static ScriptRunner scriptRunner;

    public static void init() {
        try {
            if (connection != null && !connection.isClosed()) {
    //            throw new IllegalStateException("数据库已经初始化");
                return;
            }
        } catch (SQLException e) {
            LOG.error(e.getMessage());
        }
        try {
            Class.forName(getJdbcDriver());
            connection = DriverManager.getConnection(
                    getJdbcUrl(),
                    getJdbcUsername(),
                    getJdbcPassword());
//            connection.setAutoCommit(false);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        scriptRunner = new ScriptRunner(connection, false, true);
    }

    private static String getJdbcUrl() {
        return String.format("jdbc:mysql://%1$s:%2$s/%3$s", ConfigInfo.getDbHost(), ConfigInfo.getDbPort(),ConfigInfo.getDbName());
    }

    private static String getJdbcUsername() {
        return ConfigInfo.getDbUsername();
    }

    private static String getJdbcPassword() {
        return ConfigInfo.getDbPassword();
    }

    private static String getJdbcDriver() {
        return ConfigInfo.getJdbcDriver();
    }


    public static Connection getConn() {
        try {
            if(connection==null || connection.isClosed()){
                init();
            }
        } catch (SQLException e) {
            LOG.error(e.getMessage(),e);
        }
        return connection;
    }

    public static void closeConnection() {
        try {
            if (connection!=null && !connection.isClosed()) connection.close();
        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 执行sql脚本
     *
     * @param file
     * @throws Exception
     */
    public static void executeSqlFile(File file) throws Exception {
        if (file == null || !file.exists()) {
            return;
        }
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(file),ConfigInfo.getFileCharset());
            scriptRunner.runScript(reader);
        } finally {
            FileUtils.closeQuietly(reader);
        }
    }
}